var jwt = require('jsonwebtoken');
exports.validateToken = (req) => {
  // 1.排除不需要验证token的接口、登陆、注册、轮播、产品列表... （数据需要登陆才能访问，需要验证token，反之亦然）
  // 需要验证
  // 2.前端提交token get post headers
  let token = req.headers.token || req.query.token || req.body.token
  return new Promise((resolve, reject) => {
    if (token) { // 如果token存在
      // 4.验证token合法不合法
      jwt.verify(token, 'OurVue', (err, decoded) => {
        if (err) { // token验证失败 ---  未登录状态
          reject()
        } else { // token验证成功
          req.decoded = decoded;  // 解码 
          console.log('验证成功', decoded);
          resolve()
        }
      })
    } else { // token 不存在  ----  未登录状态
      reject()
    }
  })
}

exports.sendCode = (tel, code, accessKeyId, accessKeySecret) => {
  var client = new Core({
    accessKeyId: accessKeyId,
    accessKeySecret: accessKeySecret,
    endpoint: 'https://dysmsapi.aliyuncs.com',
    apiVersion: '2017-05-25'
  });

  var params = {
    "RegionId": "cn-hangzhou",
    "PhoneNumbers": tel,
    "SignName": "吴勋勋",
    "TemplateCode": "SMS_171853298",
    "TemplateParam": "{code:"+ code +"}"
  }

  var requestOption = {
    method: 'POST'
  };

  return new Promise((resolve, reject) => {
    client.request('SendSms', params, requestOption).then((result) => {
      resolve()
      console.log(JSON.stringify(result));
    }, (ex) => {
      reject()
      console.log(ex);
    })
  })

}